﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;
using System.Web.Configuration;
using System.Web;
using System.Web.Hosting;

namespace DevToolBox.Common
{
    /// <summary>
    /// Class to access and parse values in the config file
    /// </summary>
    public static class ConfigParamReader
    {
        /// <summary>
        /// Function to read a string from the .config file
        /// </summary>
        /// <param name="key">Parameter Key</param>
        /// <returns>Parameter Value</returns>
        public static string GetString(string key)
        {
            return ConfigurationSettings.AppSettings[key];
        }

        public static void SaveString(string key, string value)
        {
            string exePath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
            Configuration config = null;

            if (File.Exists(exePath + ".config"))
            {
                //App Path for ASP.Net AJAX/MVC
                config = ConfigurationManager.OpenExeConfiguration(exePath);
            }
            else
            {
                //App Path for WCF Services
                exePath = HostingEnvironment.ApplicationVirtualPath; 
                config = WebConfigurationManager.OpenWebConfiguration(exePath);
            }

            if (!config.AppSettings.Settings.AllKeys.Contains(key))
            {
                config.AppSettings.Settings.Add(key, value);
            }
            else
            {
                config.AppSettings.Settings[key].Value = value;
            }
            config.Save();
        }

        /// <summary>
        /// Function to read an Int32 from the .config file
        /// </summary>
        /// <param name="key">Parameter Key</param>
        /// <returns>Parameter Value</returns>
        public static int GetInt32(string key)
        {
            string paramVal = GetString(key);
            return Convert.ToInt32(paramVal);
        }

        /// <summary>
        /// Function to read a Boolean from the .config file
        /// </summary>
        /// <param name="key">Parameter Key</param>
        /// <returns>Parameter Value</returns>
        public static bool GetBoolean(string key)
        {
            string paramVal = GetString(key);
            return GetString(key) == "1" ? true : false;
        }
    }
}
